package com.helloandroid

import android.content.*
import android.widget.FrameLayout
import androidx.activity.viewModels
import com.anythink.core.api.ATAdConst
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.network.toutiao.TTATRequestInfo
import com.anythink.splashad.api.ATSplashAd
import com.anythink.splashad.api.ATSplashAdListener
import com.business.TDKeys
import com.fake.FakeMainActivity
import com.helloandroid.app.model.WelcomeViewModel
import com.helloandroid.base.BaseActivity
import com.helloandroid.tools.*
import com.protol.PermissionUtil
import com.protol.ProtocolActivity
import com.protol.SharedInfoService
import dai.android.util.AndroidUtils

class WelcomeActivity : BaseActivity(), ATSplashAdListener {
    var comefrom = -1
    var splashAd: ATSplashAd? = null

    lateinit var container: FrameLayout

    // 是否完成登陆
    var loginCompleted = false
    var hasHandleJump = false

    val model: WelcomeViewModel by viewModels()

    private fun gotoMainActivity() {
        if (AppConfig.isFake) {
            val intent = Intent(this, FakeMainActivity::class.java)
            startActivity(intent)
        } else {
            val intent = Intent(this, MainActivity::class.java)
            intent.putExtra(IntentKey.ComeFromWhere, comefrom)
            MyLog.elog("========WelcomeActivity comefrom:${comefrom}==================")
            startActivity(intent)
        }
        finish()
    }

    override fun getContentViewResId() = R.layout.splash_ad_show

    override fun initView() {
        container = findViewById(R.id.splash_ad_container)

        // 出现过开屏广告 onAdDismiss 回调没有执行
        // 防止进不了 给一个10s的检查
        model.preventSplashCallback {
            MyLog.info("======== 10s 后的特殊处理!")
            if (!hasHandleJump) {
                hasHandleJump = true
                checkJump()
            }
        }
    }

    private fun initSplashAd() {
        // init ui
        val layoutParams = container.layoutParams
        layoutParams.width = resources.displayMetrics.widthPixels;
        layoutParams.height = (resources.displayMetrics.heightPixels * 0.85f).toInt();

        //v5.6.2新增，针对首次安装获取TopOn策略导致开屏广告加载超时，可传递各广告平台参数，直接发起请求
        //atMediationRequestInfo传入后，只针对首次请求开屏的情况生效，请详细阅读上方说明
        val atMediationRequestInfo = TTATRequestInfo(TDKeys.FirstSplashAppId, TDKeys.FirstSplashPlacementId, false);
        atMediationRequestInfo.adSourceId = TDKeys.FirstSplashAdSourceId;
        //splashAd = ATSplashAd(this, container, TDKeys.TopOnSplashPlacementId, atMediationRequestInfo, this)
//        splashAd = ATSplashAd(this, container, TopOnPlacementId, this);
        splashAd = ATSplashAd(this, TDKeys.TopOnSplashPlacementId, atMediationRequestInfo, this)

        //打印出此广告位下的各个广告平台广告源的相关参数（必须已经初始化过SDK且调用ATSDK.setNetworkLogDebug(true);后才会打印）
        ATSplashAd.checkSplashDefaultConfigList(this, TDKeys.TopOnSplashPlacementId, null);

        val localMap: MutableMap<String, Any> = HashMap()
        localMap[ATAdConst.KEY.AD_WIDTH] = layoutParams.width
        localMap[ATAdConst.KEY.AD_HEIGHT] = layoutParams.height
        splashAd?.let {
            it.setLocalExtra(localMap)
            if (it.isAdReady) {
                MyLog.elog("SplashAd is ready to show.")
                it.show(this, container)
            } else {
                MyLog.elog("SplashAd isn't ready to show, start to request.")
                it.loadAd()
            }
        }
    }

    override fun initData() {

        model.loadConfig { success ->
            if (!success) {
                AppUtil.serverConfig.copyFrom(ServerConfig.DefaultServerConfig)
                MyLog.error("超时-----.使用默认配置.....")
            }

            MyLog.info("AppConfig.isFake:${AppConfig.isFake}")

            // 开始正常逻辑
            // 1. 协议弹框
            if (!acceptPolicy()) {
                // 用户没有 接受协议. 跳转
                val intent = Intent(this, ProtocolActivity::class.java)
                startActivity(intent)
                finish()
                return@loadConfig
            }

            // 2. 正常逻辑
            normalLogic()
        }

        // 打印手机信息
        if (AppConfig.isDebug) {
            MyLog.info(AndroidUtils.getPhoneInfo(this))
        }
    }

    private fun normalLogic() {

        MyLog.info("===============WelcomeActivity normalLogic==========================")

        // 获取
        model.get_sysbs_from_service { sysbs ->
            // 开始登陆
            AppUtil.appViewModel().login2(sysbs) {
                loginCompleted = true
                checkJump()
                MyLog.info("set loginCompleted:${loginCompleted}")
            }
        }

        // 点击通知过来的跳转
        comefrom = intent.getIntExtra(IntentKey.ComeFromWhere, -1)
        if (comefrom == -1) {
            if (!AppConfig.isFake && AppConfig.AdToggle) {
                // 正常的启动,才显示插屏
                initSplashAd()
            } else {
                hasHandleJump = true
            }
        } else {
            hasHandleJump = true
        }
    }

    private fun acceptPolicy(): Boolean {
        // 判断是否需要弹框
        // 是否同意过用户协议，如果没有同意过用户协议，则弹出用户协议界面，同意后再重新进入开屏界面
        val shareInfoService: SharedInfoService = SharedInfoService.getInstance(this)
        // 如果是通过点击桌面进入开屏界面，动态权限没有申请到或需要显示用户协议，则需要进入协议界面
        // 如果是通过点击桌面进入开屏界面，动态权限没有申请到或需要显示用户协议，则需要进入协议界面
        if (null != intent.action &&
                (!PermissionUtil.verifyPermissions(this, PermissionUtil.PERMISSIONS) || !shareInfoService.getIsAgreeProtocol())) {
            return false
        }
        return true
    }

    private fun jumpToMainActivity() {
        if (!hasHandleJump) {
            hasHandleJump = true
        }
        checkJump()
    }

    override fun onDestroy() {
        super.onDestroy()
        splashAd?.let {
            it.onDestory()
        }
    }


    private fun checkJump() {
        if (hasHandleJump && loginCompleted) {
            gotoMainActivity()
        }
    }

    //--------------------------------------------------
    // 开屏广告回调
    override fun onAdLoaded() {
        MyLog.elog("开屏广告加载成功!")
        splashAd?.show(this, container)
    }

    override fun onNoAdError(adError: AdError?) {
        //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
        //AdError，请参考 https://docs.toponad.com/#/zh-cn/android/android_doc/android_test?id=aderror
        MyLog.elog("onNoAdError: ${adError?.fullErrorInfo}");
        jumpToMainActivity();
    }

    override fun onAdShow(p0: ATAdInfo?) {
    }

    override fun onAdClick(p0: ATAdInfo?) {
    }

    override fun onAdDismiss(p0: ATAdInfo?) {
        MyLog.info("============= onAdDismiss called!")
        jumpToMainActivity()
    }

    override fun isUseFullScreenMode(): Boolean = false
}

